﻿using Sc.Cache;
using Sc.Domain;
using Sc.Persistence;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sc.Service
{
    public class SendCarRecordService
    {
        /// <summary>
        /// 数据持久层
        /// </summary>
        protected readonly SendCarRecordDAO dao = new SendCarRecordDAO();
        /// <summary>
        /// 推送消息发送
        /// </summary>
        private readonly CommPushMessage cpm = new CommPushMessage();
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="list">业务数据</param>
        /// <returns></returns>
        public int SaveData(IList<SendCarRecord> list)
        {
            var temp = this.dao.SaveData(list);
            if (temp > 0)
            {
                var u = list.GroupBy(it => it.Driver).ToList();
                for (int i = 0; i < u.Count; i++)
                {
                    if (ProjectCache.UserToken.ContainsKey(u[i].Key))
                    {
                        MessageParam ent = new MessageParam();
                        ent.BusinessId = u[i].Key;
                        ent.Content = "您的车已派出，请查看";
                        ent.Title = "派车系统通知";
                        ent.Perfix = "DRVE";
                        var mp = ProjectCache.UserToken[ent.BusinessId];
                        if (mp.OsType == 0)
                        {
                            ent.UserAndroidToken = new List<string>();
                            ent.UserAndroidToken.Add(mp.Token);
                            cpm.PushMessageForAndroid(ent);
                        }
                        else
                        {
                            ent.UserIosToken = new List<string>();
                            ent.UserIosToken.Add(mp.Token);
                            cpm.PushMessageForIOS(ent);
                        }
                    }
                }
                //---------------------------给申请发送待办------------------------//
                var dl = list.GroupBy(it => it.CarUseNo).ToList();
                for (int i = 0; i < dl.Count; i++)
                {
                    if (ProjectCache.UserToken.ContainsKey(dl[i].Key))
                    {
                        MessageParam ent = new MessageParam();
                        ent.BusinessId = dl[i].Key;
                        ent.Content = "您的用车申请已派车，请查看";
                        ent.Title = "派车系统通知";
                        ent.Perfix = "DRVE";
                        var mp = ProjectCache.UserToken[ent.BusinessId];
                        if (mp.OsType == 0)
                        {
                            ent.UserAndroidToken = new List<string>();
                            ent.UserAndroidToken.Add(mp.Token);
                            cpm.PushMessageForAndroid(ent);
                        }
                        else
                        {
                            ent.UserIosToken = new List<string>();
                            ent.UserIosToken.Add(mp.Token);
                            cpm.PushMessageForIOS(ent);
                        }
                    }
                }
                ProjectCache.ClearCardInfo();
            }
            return temp;
        }
        /// <summary>
        /// 获取派车记录
        /// </summary>
        /// <param name="orgz">机构ID</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="pageIndex">当前第几页</param>
        /// <param name="startTime">用车开始时间</param>
        /// <param name="userName">申请人</param>
        /// <param name="end">用车结束时间</param>
        /// <param name="carNo">车牌号</param>
        /// <returns></returns>
        public CommModel<Car_UseCarApplication> GetList(int orgz, int pageSize, int pageIndex, string userName, string startTime, string end, string carNo, string carType)
        {
            string where = "AND OrgzNo=" + orgz;
            if (!string.IsNullOrEmpty(userName))
            {
                where += " AND UserName Like '%" + userName + "%'";
            }
            if (!string.IsNullOrEmpty(startTime))
            {
                where += " AND StartTime>='" + startTime + "' AND StartTime<='" + end + "'";
            }
            if (!string.IsNullOrEmpty(carNo))
            {
                where += " AND CarNo Like '%" + carNo + "%'";
            }
            if (!string.IsNullOrEmpty(carType))
            {
                where += " AND CarType = " + carType;
            }
            Hashtable param = new Hashtable();
            param.Add("A1", pageIndex);
            param.Add("A2", pageSize);
            param.Add("A3", where);
            param.Add("A4", "[VW_CarRecord]");
            param.Add("A5", "SendTime DESC");
            var ht = CommDAO.CommPagination(param);
            DataTable dt = ht["data"] as DataTable;
            List<Car_UseCarApplication> list = new List<Car_UseCarApplication>();
            foreach (DataRow item in dt.Rows)
            {
                list.Add(DataRowToModel(item));
            }
            CommModel<Car_UseCarApplication> ent = new CommModel<Car_UseCarApplication>();
            ent.Data = list;
            ent.PageCount = Convert.ToInt32(ht["PageCount"]);
            ent.RecordCount = Convert.ToInt32(ht["record"]);
            return ent;
        }



        /// <summary>
        /// 获取当前司机可还车
        /// </summary>
        /// <param name="userId">司机ID</param>
        /// <returns></returns>
        public IList<SendCarTemp> GetSendCarRecord(int userId)
        {
            return dao.GetSendCarRecord(userId);
        }

        /// <summary>
        /// 通过车牌得到车辆的未还记录
        /// </summary>
        /// <param name="carNo"></param>
        /// <returns></returns>
        public IList<SendCarTemp> GetSendCarRecordByCar(string carNo)
        {
            return dao.GetSendCarRecordByCar(carNo);
        }

        /// <summary>
        /// 更新派车纪录
        /// </summary>
        /// <param name="bid">业务ID</param>
        /// <returns></returns>
        public ReturnModel SaveReturnCar(int bid)
        {
            var re = dao.SaveReturnCar(bid);
            if (re.SourceId == 1)
                ProjectCache.ClearCardInfo();
            return re;
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Car_UseCarApplication DataRowToModel(DataRow row)
        {
            Car_UseCarApplication model = new Car_UseCarApplication();
            if (row != null)
            {
                if (row["Id"] != null && row["Id"].ToString() != "")
                {
                    model.Id = int.Parse(row["Id"].ToString());

                }
                if (row["StartAddress"] != null)
                {
                    model.StartAddress = row["StartAddress"].ToString();
                }
                if (row["EndAddress"] != null)
                {
                    model.EndAddress = row["EndAddress"].ToString();
                }
                if (row["StartTime"] != null && row["StartTime"].ToString() != "")
                {
                    model.StartTime = DateTime.Parse(row["StartTime"].ToString());
                }
                if (row["TotalCount"] != null && row["TotalCount"].ToString() != "")
                {
                    model.TotalCount = int.Parse(row["TotalCount"].ToString());
                }
                if (row["Remark"] != null)
                {
                    model.Remark = row["Remark"].ToString();
                }
                if (row["InstanceState"] != null && row["InstanceState"].ToString() != "")
                {
                    model.InstanceState = int.Parse(row["InstanceState"].ToString());
                }
                if (row["IsComplaint"] != null && row["IsComplaint"].ToString() != "")
                {
                    if ((row["IsComplaint"].ToString() == "1") || (row["IsComplaint"].ToString().ToLower() == "true"))
                    {
                        model.IsComplaint = true;
                    }
                    else
                    {
                        model.IsComplaint = false;
                    }
                }
                if (row["BussinessState"] != null && row["BussinessState"].ToString() != "")
                {
                    if ((row["BussinessState"].ToString() == "1") || (row["BussinessState"].ToString().ToLower() == "true"))
                    {
                        model.BussinessState = true;
                    }
                    else
                    {
                        model.BussinessState = false;
                    }
                }
                if (row["UserId"] != null && row["UserId"].ToString() != "")
                {
                    model.UserId = int.Parse(row["UserId"].ToString());
                }
                if (row["OrgzNo"] != null && row["OrgzNo"].ToString() != "")
                {
                    model.OrgzNo = int.Parse(row["OrgzNo"].ToString());
                }
                if (row["DriverName"] != null)
                {
                    model.DriverName = row["DriverName"].ToString();
                }
                if (row["UserName"] != null)
                {
                    model.UserName = row["UserName"].ToString();
                }
                if (row["CarNo"] != null)
                {
                    model.CarNo = row["CarNo"].ToString();
                }
                if (row["DeptName"] != null)
                {
                    model.Orgz = row["OrgzName"] + "/" + row["DeptName"];
                }
                if (row["CarTypeName"] != null)
                {
                    model.CarTypeName = row["CarTypeName"].ToString();
                }
            }
            return model;
        }

        /// <summary>
        /// 获取司机业务详细信息
        /// </summary>
        /// <param name="bid">业务ID</param>
        /// <param name="type">业务ID</param>
        /// <returns></returns>
        public List<SendCarTemp> GetSCRecord(int bid, int type)
        {
            var list = this.dao.GetSCRecord(bid, type);
            if (type == 1)
            {
                List<SendCarTemp> result = new List<SendCarTemp>();
                var tmp = list.GroupBy(it => it.Id).ToList();
                SendCarTemp ent = list.FirstOrDefault();
                ent.Driver = new List<ScModel>();
                foreach (var item in tmp)
                {
                    foreach (var em in item)
                    {
                        ScModel m = new ScModel();
                        m.CarNo = em.CarNo;
                        m.DriverName = em.DriverName;
                        m.DriverPhone = em.DriverPhone;
                        ent.Driver.Add(m);
                    }
                }
                result.Add(ent);
                return result;
            }
            else
                return list;
        }

        /// <summary>
        /// 获取单条派车记录
        /// </summary>
        /// <returns></returns>
        public Car_UseCarApplication GetSendCarRecordById(int id)
        {
            return this.dao.GetCar_UseCarApplication(id);
        }

        public Car_UseCarApplication GetSendCarRecordForPrintById(int id)
        {
            return this.dao.Ge_SendtCarPrint(id);
        }

        /// <summary>
        /// 获取派车记录
        /// </summary>
        /// <returns></returns>
        public SendCarRecordTemp GetSendCarRecordTemp(int id)
        {
            return this.dao.GetSendCarRecordTemp(id);
        }
    }
}
